#include<stdio.h>
#include<unistd.h>
#include<mysql/mysql.h>
#include<stdlib.h>
#include<string.h>


int main()
{
  //定义并初始化mysql句柄
  //mysql_init(句柄)
  MYSQL* mysql = NULL;
  mysql = mysql_init(NULL);
  if(mysql == NULL)
  {
    perror("mysql_init error");
    return -1;
  }
  //连接mysql服务器
  //mysql_real_connect(句柄，服务器IP，用户名，密码，库名称，端口，套接字文件，客户端名称)；
  if(mysql_real_connect(mysql,"127.0.0.1","root","1","vod_system",0,NULL,0) == NULL)
  {
    printf("connect mysql failed :%s\n",mysql_error(mysql));
    return -1;
  }
  //设置客户端字符编码集
  //mysql_set_character_set(句柄，字符集名称)
  int ret;
  ret = mysql_set_character_set(mysql,"utf8");
  if(ret != 0)
  {
    printf("set character failed:%s\n",mysql_error(mysql));
    return -1;
  }
  //切换选择数据库
  //mysql_select_db(mysql,"vod_system");
  
  //拼装sql语句
  //char* insert = "insert tb_vedio values(null,'安江大战吴昊','一部好看的家庭伦理片','/vedio/popo.mp4','/image/popo.jpg',now();)";
  
  //执行语句mysql_query(句柄，语句)
  //char* update = "update tb_vedio set vdes = '婆媳纷争片' where id = 2;";
  //char* delete = "delete from tb_vedio where id = 2;";
  const char* select = "select * from tb_vedio;"; //“”字符串是常量，加上const类型匹配
  ret = mysql_query(mysql,select);
  if(ret != 0)
  {
    printf("query sql failed: %s\n",mysql_error(mysql));
    return -1;
  }
  //保存结果集到本地
  //MYSQL_RES* mysql_store_result(句柄)
  MYSQL_RES* res = mysql_store_result(mysql);
  if(res == NULL)
  {
    printf("store result dailed :%s\n",mysql_error(mysql));
    return -1;
  }
  //获取结果集的条数和列数
  // mysql_num_rows(结果集)   mysql_num_fields(结果集)
  int row_num = mysql_num_rows(res);
  int col_num = mysql_num_fields(res);
  for(int i = 0;i<row_num;++i)
  {
    //遍历逐条取出结果集中的每一条数据 MYSQL_ROW  mysql_fetch_row(结果集)
    MYSQL_ROW row = mysql_fetch_row(res);
    for(int j = 0;j<col_num;j++)
    {
      printf("%s\t", row[j]);
    }
    printf("\n");
  }
  //释放结果集
  //mysql_free_result(结果集)
  mysql_free_result(res);

  //关闭句柄释放资源
  mysql_close(mysql);
  return 0;
}
